"""采购申请相关路由"""
import json
from flask import request
from flask_restful import Resource
from .. import db
from ..models import PurchaseApplication, Employee
from ..utils.helpers import success_response, error_response, handle_errors
from ..utils.flowable_client import FlowableClient
try:
    from server.config.config import Config  # type: ignore
except ModuleNotFoundError:
    from config.config import Config  # type: ignore

class PurchaseApplicationResource(Resource):
    """采购申请提交与列表"""
    def __init__(self):
        self.flowable_client = FlowableClient(
            Config.FLOWABLE_REST_URL,
            Config.FLOWABLE_REST_USER,
            Config.FLOWABLE_REST_PASSWORD
        )

    @handle_errors
    def post(self):
        data = request.get_json() or {}
        required = ['applicant_id', 'purchase_amount', 'items', 'project_id']
        for f in required:
            if f not in data:
                return error_response(f'缺少必填字段: {f}', 400)
        # 校验金额
        try:
            amount = float(data['purchase_amount'])
        except ValueError:
            return error_response('purchase_amount 必须为数字', 400)
        if amount <= 0:
            return error_response('purchase_amount 必须大于 0', 400)
        # 校验 items: 期望是列表
        items = data['items']
        if not isinstance(items, list) or len(items) == 0:
            return error_response('items 必须为非空列表', 400)

        # 验证员工存在
        applicant = Employee.query.filter_by(employee_id=data['applicant_id']).first()
        if not applicant:
            return error_response('员工不存在', 404)

        # 校验 project_id
        try:
            project_id_val = int(data['project_id'])
        except (ValueError, TypeError):
            return error_response('project_id 必须为整数', 400)

        # 查找审批人：项目经理、采购部、财务、子公司负责人
        project_manager = Employee.query.filter_by(position='项目经理', company=applicant.company, status='active').first()
        if not project_manager:
            return error_response('未找到审批人（项目经理）', 400)
        purchase_dept = Employee.query.filter_by(position='采购主管', company=applicant.company, status='active').first()
        if not purchase_dept:
            return error_response('未找到审批人（采购主管）', 400)
        finance_dept = Employee.query.filter_by(position='财务主管', company=applicant.company, status='active').first()
        if not finance_dept:
            return error_response('未找到审批人（财务主管）', 400)
        subsidiary_manager = Employee.query.filter_by(position='子公司负责人', company=applicant.company, status='active').first()
        # 子公司负责人可能只有在金额>阈值时使用，可允许为空：流程中条件分支会跳过

        # 创建采购申请
        purchase_app = PurchaseApplication(
            applicant_id=applicant.employee_id,
            purchase_amount=amount,
            items_json=json.dumps(items, ensure_ascii=False),
            status='pending',
            project_id=project_id_val
        )
        db.session.add(purchase_app)
        db.session.commit()

        # Flowable 流程变量
        process_variables = {
            'serviceHost': Config.SERVICE_HOST,
            'applicantId': applicant.employee_id,
            'purchaseAmount': amount,
            'items': json.dumps(items, ensure_ascii=False),
            'applicationId': purchase_app.id,
            'projectId': project_id_val,
            'projectManagerId': project_manager.employee_id,
            'purchaseDeptAssignee': purchase_dept.employee_id,
            'financeDeptAssignee': finance_dept.employee_id,
        }
        if subsidiary_manager:
            process_variables['subsidiaryManagerAssignee'] = subsidiary_manager.employee_id

        try:
            bk = f"{applicant.employee_id}:{purchase_app.id}"
            process_instance = self.flowable_client.start_process_instance(
                process_definition_key='purchaseApproval',
                variables=process_variables,
                business_key=bk
            )
            purchase_app.process_instance_id = process_instance['id']
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            return error_response(f'启动流程失败: {str(e)}', 500)
        # Per latest specification, success responses should use HTTP 200 rather than 201
        return success_response({
            'application': purchase_app.to_dict(),
            'process_instance_id': purchase_app.process_instance_id,
            'business_key': bk
        }, '采购申请提交成功', 200)

    @handle_errors
    def get(self):
        # 简单查询接口: 支持 applicant_id / status 过滤
        applicant_id = request.args.get('applicant_id')
        status = request.args.get('status')
        query = PurchaseApplication.query
        if applicant_id:
            query = query.filter_by(applicant_id=applicant_id)
        if status:
            query = query.filter_by(status=status)
        apps = query.order_by(PurchaseApplication.created_at.desc()).all()
        return success_response([a.to_dict() for a in apps])

class PurchaseGenerateResource(Resource):
    """由流程 ServiceTask 调用生成采购单的回调接口"""

    @handle_errors
    def post(self):
        data = request.get_json() or {}
        required = ['processInstanceId', 'purchaseAmount', 'items', 'applicantId']
        for f in required:
            if f not in data:
                return error_response(f'缺少必填字段: {f}', 400)
        # 查找对应的采购申请记录（根据流程实例或 applicantId + amount 模糊匹配）
        app = PurchaseApplication.query.filter_by(process_instance_id=data['processInstanceId']).first()
        if not app:
            # 回退: 按 applicant + amount 最近一条 pending
            app = PurchaseApplication.query.filter_by(applicant_id=data['applicantId'], status='pending').order_by(PurchaseApplication.created_at.desc()).first()
            if not app:
                return error_response('未找到匹配的采购申请记录', 404)
        # 更新状态为 approved (或 generated) 根据业务需要
        app.status = 'approved'
        db.session.commit()
        return success_response({'application': app.to_dict()}, '采购单生成回调处理成功')
